package com.example.CollaborativeDiscussionLearning.service.loginAndRegisterService;

import com.example.CollaborativeDiscussionLearning.component.jwt.JwtUtil;
import com.example.CollaborativeDiscussionLearning.dto.ChatUserDTO;
import com.example.CollaborativeDiscussionLearning.entity.ChatUser;
import com.example.CollaborativeDiscussionLearning.entity.UserRoom;
import com.example.CollaborativeDiscussionLearning.A.ChatRoomMapping;
import com.example.CollaborativeDiscussionLearning.mapper.ChatRoomMapper;
import com.example.CollaborativeDiscussionLearning.vo.ResponseDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Optional;
/**
* @Description: 登录注册接口实现类
* @Author: Junior
* @Date: 2023/10/13
*/
@Service
@Slf4j
public class LoginAndRegisterServiceImpl implements LoginAndRegisterService{

    @Resource
    private ChatRoomMapper chatRoomMapper;


    /**
     * 登录
     * */
    @Override
    public ResponseDataVO login(HttpServletRequest request, HttpServletResponse response, String code, String password) throws IOException {

        ChatUserDTO chatUserDTO = ChatUserDTO.builder()
                .code(code)
                .build();
        ChatUser chatUser = ChatRoomMapping.INSTANCE.chatUserDTOToChatUser(chatUserDTO);

        // 通过用户邮箱获取用户信息
        ChatUser existUser = chatRoomMapper.queryUser(chatUser);
        Optional<ChatUser> optionalChatUser = Optional.ofNullable(existUser);

        if (optionalChatUser.isPresent()) {
            // 校验密码
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

            if (passwordEncoder.matches(password, existUser.getPassword())) {
                // 校验成功设置 cookie
                setCookie(response, code);
                log.info("当前登录用户为："+existUser.toString());
                return ResponseDataVO.success(existUser.getRole());
            } else {
                return ResponseDataVO.fail("登录失败，请检查用户名和密码！！");
            }
        }
        return ResponseDataVO.fail("用户不存在，请先注册！！");
    }


    /**
     * 注册
     * */
    @Override
    public ResponseDataVO register(String name, String code, String role) {
        //初始密码设置为12345678
        String password = "12345678";
        // 加密用户密码，然后获取插入用户对象
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String hashedPassword = passwordEncoder.encode(password);
        ChatUserDTO newUserDTO = ChatUserDTO.builder()
                .name(name)
                .code(code)
                .password(hashedPassword)
                .role(role)
                .build();
        ChatUser newUser = ChatRoomMapping.INSTANCE.chatUserDTOToChatUser(newUserDTO);

        // 先校验邮箱是否被占用
        ChatUser existUser = chatRoomMapper.queryUser(newUser);
        Optional<ChatUser> optionalChatUser = Optional.ofNullable(existUser);
        if (!optionalChatUser.isPresent()) {
            // 当前邮箱未被使用，用户才能注册成功
            chatRoomMapper.insertUser(newUser);
            //添加新建用户和默认公共聊天室的关系
            UserRoom userRoom=new UserRoom();
            userRoom.setRoomId(1);
            userRoom.setUserCode(newUser.getCode());
            userRoom.setCreateTime(LocalDateTime.now());
            chatRoomMapper.insertUserRoom(userRoom);
            return ResponseDataVO.success("注册成功");
        }
        return ResponseDataVO.fail("注册失败，当前邮箱已被使用");
    }



    /**
    * 生成 jwt 加密同时保存到 cookies 中
    * @param response:  response
	* @param email:  email
    * @return: void
    * @Author: Junior
    * @Date: 2023/10/17
    */
    public static void setCookie(HttpServletResponse response, String email) {
        String token = JwtUtil.createToken(email);
        String tokenValue = token.split(" ")[1];
        Cookie cookie = new Cookie(JwtUtil.USER_LOGIN_TOKEN, tokenValue);
        cookie.setMaxAge(3600);
        response.addCookie(cookie);
    }

    /**
    * 从 request 中获取到用户信息
    * @param request:  request
    * @return: com.example.junior.dto.ChatUserDTO
    * @Author: Junior
    * @Date: 2023/10/17
    */
    public ChatUserDTO jwtInfo(HttpServletRequest request) {

        String code = request.getSession().getAttribute("sub").toString();
        ChatUser chatUser = ChatUser.builder()
                .code(code).build();

        return ChatRoomMapping.INSTANCE.chatUserToChatUserDTO(chatRoomMapper.queryUser(chatUser));
    }
}
